package com.xuhai.blog.common.shiro;

import com.alibaba.fastjson.JSON;
import com.xuhai.blog.admin.entity.ExpiresEntity;
import com.xuhai.blog.admin.service.ExpiresService;
import com.xuhai.blog.common.exception.RTException;
import com.xuhai.blog.common.util.ResultJson;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 3.自定义shiro过滤器
 * @Author PangJunjie
 * @Date 2022/2/9/009
 */
public class Shiro2Filter extends AuthenticatingFilter {

    /*获取或创建应用于shiro的token值*/
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        String token=getToken(servletRequest);
        if(StringUtils.isBlank(token)){
            return null;
        }
        return new Shiro2Token(token);
    }

    /*目前主流的浏览器都会发送两次请求，其中一次为option请求表示测试用。对于后台是无意义的，无需处理的。我们在这把他过滤掉*/
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest)request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = getToken(servletRequest);
        /*转换response*/
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /*转换request*/
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        /*处理中文乱码*/
        response.setContentType("application/json;charset=utf-8");
        /*解决跨域*/
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        if (StringUtils.isBlank(token)) {
            /*输出JSON*/
            response.getWriter().println(JSON.toJSON(ResultJson.error(401, "未携带token")));
            return false;
        }
        /*放行*/
        return executeLogin(servletRequest, servletResponse);
    }

    /*获取token*/
    private String getToken(ServletRequest servletRequest){
        /*request转换*/
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        /*从header中获取token*/
        String token = request.getHeader("token");
        /*header中如果不存在，则去参数中获取*/
        if(StringUtils.isBlank(token)){
            token=request.getParameter("token");
        }
        return token;
    }
}
